package com.bmps.springcloud.insuredmicroservice.service.cloudplatform;

import com.bmps.springcloud.common.response.CloudPlatModel;
import com.bmps.springcloud.common.utils.DateUtil;
import com.bmps.springcloud.insuredmicroservice.constant.accept.AcceptConstant;
import com.bmps.springcloud.insuredmicroservice.model.accept.resquest.*;
import com.bmps.springcloud.insuredmicroservice.model.cloudplatform.ChannelEnum;
import com.bmps.springcloud.insuredmicroservice.model.cloudplatform.InsureProvinceEnum;
import com.bmps.springcloud.insuredmicroservice.model.cloudplatform.SubPermission;
import com.bmps.springcloud.insuredmicroservice.repository.cloudplatform.coresystem.CloudPlatformRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 获取参与保盾云评分人员列表
 *
 * @author llz
 * @date 2019/08/16
 */
@Service
public class CloudPlatformServiceImpl implements CloudPlatformService {

    private final CloudPlatformRepository cloudPlatform;

    private final RedisTemplate redisTemplate;

    /**
     * subpermission 险类类型1
     */
    private static final int SUBPERMISSION_TYPE1 = 1;

    /**
     * subpermission 险类类型2
     */
    private static final int SUBPERMISSION_TYPE2 = 2;

    /**
     * subpermission 险类类型3
     */
    private static final int SUBPERMISSION_TYPE3 = 3;

    public CloudPlatformServiceImpl(CloudPlatformRepository cloudPlatform,
                                    RedisTemplate redisTemplate) {
        this.cloudPlatform = cloudPlatform;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean checkHmRisk(List<String> riskCodeList) {
        if (riskCodeList.size() > 0) {
            for (String riskCode : riskCodeList) {
                Object obj = redisTemplate.opsForValue().get(AcceptConstant.REDIS_PREFIX_R004 + "|" + riskCode);
                if (obj != null) {
                    String[] a = String.valueOf(obj).split("\\|");
                    if (StringUtils.equals(a[4], "1") || StringUtils.equals(a[4], "2")) {
                        return true;
                    }
                } else {
                    String riskType = cloudPlatform.checkHmRiskType(riskCode);
                    if (StringUtils.equals("1", riskType) || StringUtils.equals(riskType, "2")) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean getHmRiskList(List<ProductModel> produltList, List<ProductModel> prodIsHmRiskList, List<ProductModel> prodNoHmRiskList) {

        boolean isHMFlag = false;
        for (ProductModel productModel : produltList) {
            Object obj = redisTemplate.opsForValue().get(AcceptConstant.REDIS_PREFIX_R004 + "|" + productModel.getProdCode());
            if (obj != null) {
                String[] a = String.valueOf(obj).split("\\|");
                if (StringUtils.equals(a[4], "1") || StringUtils.equals(a[4], "2")) {
                    prodIsHmRiskList.add(productModel);
                    isHMFlag = true;
                } else {
                    prodNoHmRiskList.add(productModel);
                }
            } else {
                prodNoHmRiskList.add(productModel);
            }
        }
        return isHMFlag;

    }

    /**
     * 校验产品是否调用保盾云
     *
     * @param riskCode   险种
     * @param agencyCode 机构
     * @param saleChnl   销售渠道
     * @return true-调用
     */
    private boolean check(String riskCode, String agencyCode, String saleChnl) {
        String vLine = "|";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(AcceptConstant.REDIS_PREFIX_B001).append(saleChnl).append(vLine).append(agencyCode);
        Object obj = redisTemplate.opsForValue().get(stringBuilder.toString());
        if (obj == null) {
            stringBuilder.setLength(0);
            stringBuilder.append(AcceptConstant.REDIS_PREFIX_B002).append(saleChnl).append("|").append(agencyCode).append("|").append(riskCode);
            obj = redisTemplate.opsForValue().get(stringBuilder.toString());
            if (obj == null) {
                return false;
            }
        }
        Boolean member = redisTemplate.opsForSet().isMember(AcceptConstant.REDIS_PREFIX_B003, riskCode);
        return member == null ? false : member.booleanValue();
    }

    private boolean exemptionProduct(String riskCode) {
        Object obj = redisTemplate.opsForValue().get(AcceptConstant.REDIS_PREFIX_R004 + "|" + riskCode);
        if (obj != null) {
            String[] result = String.valueOf(obj).split("\\|");
            return (StringUtils.equals(result[4], "1") || StringUtils.equals(result[4], "2"));
        }
        return false;
    }

    @Override
    public List<String> getProdCodeByInsSeq(Integer insSeq, List<ProductModel> productModelList) {
        List<String> prodCodeList = new ArrayList<>();
        for (ProductModel productModel : productModelList) {
            if (productModel.getProdInsSeq() == insSeq) {
                prodCodeList.add(productModel.getProdCode());
            }
        }
        return prodCodeList;
    }

    /**
     * 险种，渠道，管理结构校验
     *
     * @param salechnl     销售渠道
     * @param agentCom     管理机构
     * @param riskCodeList 险种序号列表
     * @return boolean
     */
    @Override
    public boolean checkData(String salechnl, String agentCom,
                             List<String> riskCodeList) {
        Object obj = redisTemplate.opsForValue().get(AcceptConstant.REDIS_PREFIX_B001 + "|" + "agentcom" + "|" + salechnl + "|" + agentCom);
        if (obj != null) {
            return true;
        }
        if (riskCodeList.size() > 0) {
            for (String riskCode : riskCodeList) {
                StringBuilder strb = new StringBuilder(16);
                strb.append(AcceptConstant.REDIS_PREFIX_B002).append("|").append("riskcode").append("|").append(salechnl).append("|").append(agentCom).append("|").append(riskCode);
                Object strobj = redisTemplate.opsForValue().get(strb.toString());
                if (strobj != null) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 险类判断(注：1,2为1；单独3为2；带3就3，如：1,3为3)
     *
     * @param prodRiskList 险种列表
     * @return int
     */
    private int subpermissionType(List<ProductModel> prodRiskList) {
        if (prodRiskList.size() == 1 && SubPermission.getPermissionTypeByProdCode(prodRiskList.get(0).getProdCode()) == SUBPERMISSION_TYPE3) {
            return SUBPERMISSION_TYPE2;
        } else {
            for (ProductModel productModel : prodRiskList) {
                int subType = SubPermission.getPermissionTypeByProdCode(productModel.getProdCode());
                if (subType == SUBPERMISSION_TYPE3) {
                    return SUBPERMISSION_TYPE3;
                }
            }
        }
        return SUBPERMISSION_TYPE1;
    }

    @Override
    public HashSet<CloudPlatModel> checkCloudPlatForm(AcceptRequestDataModel acceptRequestDataModel) {
        PolicyInfoModel policyInfo = acceptRequestDataModel.getRequest().getPolicyInfo();
        String manageCom = policyInfo.getManageCom().substring(0, 4);
        int insurantPro = InsureProvinceEnum.getCodeByManageCom(manageCom);
        String effectTime = DateUtil.format(policyInfo.getCvalidate(), "yyyy/MM/dd");
        int channel = ChannelEnum.getCloudChanlByOnlineChanl(Integer.valueOf(policyInfo.getSaleChnl()));
        //产品信息列表
        List<ProductModel> produltList = acceptRequestDataModel.getRequest().getProductInfo().getProducts().getProduct();
        HashSet<CloudPlatModel> cloudPlatHashSet = new HashSet<>();
        for (ProductModel productModel : produltList) {
            String riskCode = productModel.getProdCode();
            //渠道下改产品是否调用保盾云
            if (check(riskCode, policyInfo.getAgencyCode(), policyInfo.getSaleChnl())) {
                //豁免险（豁免责任的判断暂时不加）
                if (exemptionProduct(riskCode)) {
                    AppntModel appntModel = acceptRequestDataModel.getRequest().getCustInfo().getAppnt();
                    if (appntModel.getIsWhite() == 0) {
                        //是否调用保盾云
                        appntModel.setIsCall(1);
                        CloudPlatModel cloudPlat = new CloudPlatModel();
                        cloudPlat.setId(appntModel.getIdNo());
                        cloudPlat.setName(appntModel.getAppntName());
                        cloudPlat.setPhone(appntModel.getMobile());
                        String socialInsuFlag = appntModel.getSocialInsuFlag();
                        cloudPlat.setSocialIdentity(StringUtils.isEmpty(socialInsuFlag) ? 5 : Integer.valueOf(socialInsuFlag));
                        cloudPlat.setEffectiveTime(effectTime);
                        cloudPlat.setInsureProvince(insurantPro);
                        cloudPlat.setInseq(0);
                        cloudPlat.setChannel(channel);
                        cloudPlat.setPolicyno(policyInfo.getContNo());
                        cloudPlat.setPermission(1);
                        cloudPlatHashSet.add(cloudPlat);
                    }
                } else {
                    //被保人列表
                    List<InsurantModel> insurantList = acceptRequestDataModel.getRequest().getCustInfo().getInsurants().getInsurant();
                    for (InsurantModel insurantModel : insurantList) {
                        if (insurantModel.getInsSeq() == productModel.getProdInsSeq()) {
                            CloudPlatModel cloudPlat = new CloudPlatModel();
                            if (insurantModel.getIsWhite() == 0) {
                                insurantModel.setIsCall(1);
                                cloudPlat.setInseq(insurantModel.getInsSeq());
                                cloudPlat.setChannel(channel);
                                cloudPlat.setPolicyno(policyInfo.getContNo());
                                cloudPlat.setPermission(1);
                                String socialInsuFlag = insurantModel.getSocialInsuFlag();
                                cloudPlat.setSocialIdentity(StringUtils.isEmpty(socialInsuFlag) ? 5 : Integer.valueOf(socialInsuFlag));
                                cloudPlat.setEffectiveTime(effectTime);
                                cloudPlat.setInsureProvince(insurantPro);
                                cloudPlat.setId(insurantModel.getIdNo());
                                cloudPlat.setName(insurantModel.getName());
                                cloudPlat.setPhone(insurantModel.getMobile());
                                cloudPlatHashSet.add(cloudPlat);
                            }
                            break;
                        }
                    }
                }

            }

        }
        acceptRequestDataModel.getRequest().getPolicyInfo().setCloudPlatNumber(String.valueOf(cloudPlatHashSet.size()));
        return cloudPlatHashSet;
    }

//    @Override
//    public HashSet<CloudPlatModel> checkCloudPlatForm(AcceptRequestDataModel acceptRequestDataModel) {
//        //被保人列表
//        List<InsurantModel> insurantList = acceptRequestDataModel.getRequest().getCustInfo().getInsurants().getInsurant();
//        AppntModel appntModel = acceptRequestDataModel.getRequest().getCustInfo().getAppnt();
//        PolicyInfoModel policyInfo = acceptRequestDataModel.getRequest().getPolicyInfo();
//        String agentCom = policyInfo.getAgencyCode();
//        int channel = ChannelEnum.getCloudChanlByOnlineChanl(Integer.valueOf(policyInfo.getSaleChnl()));
//        String contNo = policyInfo.getContNo();
//        //产品信息列表
//        List<ProductModel> produltList = acceptRequestDataModel.getRequest().getProductInfo().getProducts().getProduct();
//        HashSet<CloudPlatModel> cloudPlatHashSet = new HashSet<>();
//
//        //查找产品列表中是否存在豁免险
//        List<ProductModel> prodNoHmRiskList = new ArrayList<>();
//        List<ProductModel> prodIsHmRiskList = new ArrayList<>();
//        boolean exemptionInsurance = getHmRiskList(produltList,prodIsHmRiskList,prodNoHmRiskList);
//        if (exemptionInsurance) {
//            //判断寿险
//            int sutType = subpermissionType(prodIsHmRiskList);
//            if (appntModel.getIsWhite() == 0) {
//                //是否调用保盾云
//                appntModel.setIsCall(1);
//                CloudPlatModel cloudPlat = new CloudPlatModel();
//                cloudPlat.setId(appntModel.getIdNo());
//                cloudPlat.setName(appntModel.getAppntName());
//                cloudPlat.setPhone(appntModel.getMobile());
//                cloudPlat.setSex(Integer.valueOf(appntModel.getAppntSex()));
//                cloudPlat.setBirthday(DateUtil.format(appntModel.getAppntBirthday(),"yyyy/MM/dd"));
//                cloudPlat.setInseq(0);
//                cloudPlat.setChannel(channel);
//                cloudPlat.setPolicyno(contNo);
//                cloudPlat.setPermission(1);
//                cloudPlat.setSubpermission(sutType);
//                cloudPlatHashSet.add(cloudPlat);
//            }
//        }
//        for (InsurantModel insurantModel : insurantList) {
//            CloudPlatModel cloudPlat = new CloudPlatModel();
//            List<String> prodCodeList = getProdCodeByInsSeq(insurantModel.getInsSeq(), prodNoHmRiskList);
//            //险种，渠道，管理结构校验
//            boolean checkData = checkData(policyInfo.getSaleChnl(), agentCom, prodCodeList);
//            if (checkData) {
//                //被保人白名单校验
//                if (insurantModel.getIsWhite() == 0) {
//                    int subType = subpermissionType(prodNoHmRiskList);
//
//                    insurantModel.setIsCall(1);
//                    //加被保人
//                    cloudPlat.setInseq(insurantModel.getInsSeq());
//                    cloudPlat.setChannel(channel);
//                    cloudPlat.setPolicyno(contNo);
//                    cloudPlat.setPermission(1);
//                    cloudPlat.setSubpermission(subType);
//                    cloudPlat.setId(insurantModel.getIdNo());
//                    cloudPlat.setName(insurantModel.getName());
//                    cloudPlat.setPhone(insurantModel.getMobile());
//                    cloudPlat.setSex(Integer.valueOf(insurantModel.getSex()));
//                    cloudPlat.setBirthday(DateUtil.format(insurantModel.getBirthday(),"yyyy/MM/dd"));
//                    cloudPlatHashSet.add(cloudPlat);
//                }
//            }
//        }
//        acceptRequestDataModel.getRequest().getPolicyInfo().setCloudPlatNumber(String.valueOf(cloudPlatHashSet.size()));
//        return cloudPlatHashSet;
//    }
}
